package com.qd.panda.service.shop.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.shop.product.ProductDTO;
import com.qd.common.panda.domain.entity.shop.product.ProductDetailDTO;
import com.qd.common.panda.domain.entity.shop.product.ProductImgDTO;
import com.qd.common.sys.domain.entity.upload.FileUploadDTO;
import com.qd.panda.mapper.shop.product.ProductMapper;
import com.qd.panda.model.Product;
import com.qd.panda.model.ProductImg;
import com.qd.panda.service.stroke.BigDecimalUtil;
import com.qd.system.util.FileConfirmUtil;
import com.qd.upload.constant.FileConfirmDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 商品信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ProductService extends BaseService<ProductMapper, Product> {

    private static final String PREFIX_ID = "panda_product_productCode_{0}";
    private final ProductDetailService productDetailService;
    private final ProductImgService productImgService;

    private final RedisTemplateUtil<Product> redisTemplateUtil;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */

    @Transactional(rollbackFor = Exception.class)
    public ProductDTO save(ProductDTO dto) {
        validator(dto);
        final Product model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */

    @Transactional(rollbackFor = Exception.class)
    public ProductDTO update(ProductDTO dto) {
        validator(dto);
        final Product historyModel = Optional.ofNullable(getById(dto.getProductCode())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final Product model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */

    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<Product> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */

    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<Product> mList) {
        final List<String> ids = mList.stream().map(Product::getProductCode).collect(toList());
        final List<Product> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param productCode 主键
     */

    @Transactional(rollbackFor = Exception.class)
    public void removeById(String productCode) {
        final Product historyModel = Optional.ofNullable(getById(productCode)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(productCode)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */

    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<Product> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */

    @Transactional(readOnly = true)
    public Boolean isExists(ProductDTO dto) {
        final QueryWrapper<Product> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param productCode 主键
     * @return 存在为true
     */

    @Transactional(readOnly = true)
    public Boolean isExistsById(String productCode) {
        boolean exists = false;
        if (StringUtils.hasLength(productCode)) {
            final Product model = getById(productCode);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param productCode 主键
     * @return 单条记录
     */

    @Transactional(readOnly = true)
    public Product getById(String productCode) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, productCode);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(productCode), Product.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param productCode 主键
     * @return 单条记录，转换成页面对象
     */

    @Transactional(readOnly = true)
    public ProductDTO getByIdDto(String productCode) {
        return Optional.ofNullable(getById(productCode)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */

    @Transactional(readOnly = true)
    public Product getOne(ProductDTO dto) {
        final QueryWrapper<Product> queryWrapper = createQueryWrapper(dto);
        Product model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */

    @Transactional(readOnly = true)
    public ProductDTO getOneDto(ProductDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */

    @Transactional(readOnly = true)
    public List<Product> getList(ProductDTO dto) {
        final QueryWrapper<Product> queryWrapper = createQueryWrapper(dto);
        final List<Product> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */

    @Transactional(readOnly = true)
    public List<ProductDTO> getListDto(ProductDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */

    @Transactional(readOnly = true)
    public IPage<ProductDTO> page(Page<Product> page, ProductDTO dto) {
        final QueryWrapper<Product> queryWrapper = createQueryWrapper(dto);
        Page<Product> iPage = baseMapper.selectPage(page, queryWrapper);
        queryWrapper.clear();
        return iPage.convert(product -> modelToDto(product, false));
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */

    public void clearCache(Product model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getProductCode()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */

    public void clearCaches(List<Product> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getProductCode())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    public ProductDTO modelToDto(Product model) {
        return modelToDto(model, true);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */

    public ProductDTO modelToDto(Product model, boolean isDetail) {
        if (null == model) {
            return null;
        }
        final ProductDTO dto = new ProductDTO();
        dto.setProductCode(model.getProductCode());
        dto.setName(model.getName());
        dto.setPrice(model.getPrice());
        dto.setStock(model.getStock());
        dto.setPicUrl(model.getPicUrl());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setState(model.getState());
        dto.setFactory(model.getFactory());
        buildDisplay(dto, isDetail);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */

    public Product dtoToModel(ProductDTO dto) {
        if (null == dto) {
            return null;
        }
        final Product model = new Product();
        model.setProductCode(dto.getProductCode());
        model.setName(dto.getName());
        model.setPrice(dto.getPrice());
        model.setStock(dto.getStock());
        model.setPicUrl(dto.getPicUrl());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setState(dto.getState());
        model.setFactory(dto.getFactory());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(ProductDTO dto, boolean isDetail) {
        dto.setPicUrl(FileConfirmUtil.getImageFile(dto.getPicUrl()));
        dto.setPriceDisplay(BigDecimalUtil.buildDefaultScale(dto.getPrice()).stripTrailingZeros().toPlainString());
        if (isDetail) {
            Optional.ofNullable(productDetailService.getByIdDto(dto.getProductCode())).ifPresent(d -> dto.setDetail(d.getDetail()));
            dto.setImgList(Optional.ofNullable(productImgService.getListByProductCodeDto(dto.getProductCode())).orElse(Collections.emptyList()));
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */

    public List<ProductDTO> modelToDtoList(List<Product> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */

    public List<Product> dtoToModelList(List<ProductDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<Product> createQueryWrapper(ProductDTO dto) {
        final QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(dto.getName())) {
                queryWrapper.like("name", dto.getName());
            }
            if (null != dto.getState()) {
                queryWrapper.eq("state", dto.getState());
            }
        }
        queryWrapper.orderByDesc("add_time");
        queryWrapper.orderByDesc("state");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */

    public List<Product> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<Product> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(Product::getProductCode).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    private void validator(ProductDTO dto) {
        BigDecimal price = dto.getPrice();
        if (price.doubleValue() < 0.01) {
            throw new ApiException("商品单价不能小于0.01");
        }
        if (price.doubleValue() > 9999) {
            throw new ApiException("商品单价不能大于9999");
        }
        Integer state = dto.getState();
        if (state.equals(0)) {
            //上架
            if (null == dto.getAddTime()) {
                dto.setAddTime(LocalDateTime.now());
            }
        }
        ProductDetailDTO detail = productDetailService.getByIdDto(dto.getProductCode());
        if (null == detail) {
            detail = new ProductDetailDTO();
            detail.setProductCode(dto.getProductCode());
            detail.setDetail(dto.getDetail());
            productDetailService.save(detail);
        } else {
            detail.setDetail(dto.getDetail());
            productDetailService.update(detail);
        }
        if (!dto.getPicUrl().startsWith(ConstantDto.HTTP) && !dto.getPicUrl().startsWith(ConstantDto.HTTPS)) {
            FileConfirmDTO fileConfirmDto = FileConfirmUtil.singleFileConfirm(dto.getPicUrl(), ConstantDto.ATTACHMENTTYPE_2);
            if (null == fileConfirmDto) {
                throw new ApiException("文件ID不存在[" + dto.getPicUrl() + "]");
            }
            dto.setPicUrl(fileConfirmDto.getOfficialFile());
        } else {
            dto.setPicUrl(null);
        }
        List<ProductImgDTO> imgList = dto.getImgList();
        if (null != imgList && !imgList.isEmpty()) {
            List<ProductImg> imgModelList = imgList.stream().filter(img -> StringUtils.hasLength(img.getFileId())).map(d -> {
                FileUploadDTO fileUploadDto = new FileUploadDTO();
                fileUploadDto.setId(d.getFileId());
                fileUploadDto.setAttachmentType(d.getAttachmentType());
                FileConfirmDTO fileConfirmDto = FileConfirmUtil.singleFileConfirm(fileUploadDto.getId(), fileUploadDto.getAttachmentType());
                if (null == fileConfirmDto) {
                    throw new ApiException("文件ID不存在[" + fileUploadDto.getId() + "]");
                }
                ProductImg productImg = new ProductImg();
                productImg.setId(fileConfirmDto.getFileId());
                productImg.setProductCode(dto.getProductCode());
                productImg.setPicPath(fileConfirmDto.getOfficialFile());
                if (null != d.getIdx() && d.getIdx() > 0) {
                    productImg.setIdx(d.getIdx());
                }
                if (StringUtils.hasLength(d.getPicName())) {
                    productImg.setPicName(d.getPicName());
                } else {
                    productImg.setPicName(fileConfirmDto.getFileName());
                }
                fileConfirmDto.freeData();
                return productImg;
            }).collect(toList());
            if (!imgModelList.isEmpty()) {
                productImgService.saveBatch(imgModelList);
            }
        }

    }

    @Transactional(readOnly = true)
    public String idToDisplay(String productCode) {
        String name = "";
        if (StringUtils.hasLength(productCode)) {
            final Product product = getById(productCode);
            name = (null == product ? "" : product.getName());
        }
        return name;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateState(ProductDTO dto) {
        Product product = Optional.ofNullable(getById(dto.getProductCode())).orElseThrow(() -> new ApiException("主键值错误"));
        if (!product.getState().equals(dto.getState())) {
            product.setState(dto.getState());
            if (product.getState().equals(0)) {
                //上架
                product.setAddTime(LocalDateTime.now());
            }
            try {
                updateById(product);
            } finally {
                clearCache(product);
            }
        }
        product.freeData();
        dto.freeData();
    }
}